package com.example.springbootintegration.controller;

import com.example.springbootintegration.common.PageVo;
import com.example.springbootintegration.common.R;
import com.example.springbootintegration.entity.User;
import com.example.springbootintegration.exception.ResourceNotFoundException;
import com.example.springbootintegration.service.UserService;
import com.example.springbootintegration.vo.QueryVo;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.List;
import java.util.UUID;

/**
 * @auther: zhangxin
 * @Description:
 */
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @ResponseStatus(HttpStatus.OK)
    @GetMapping("")
    public R<PageVo<User>> findByPage(PageVo pageVo, QueryVo queryVo) {
        PageInfo<User> pageInfo =  userService.selectByPage(pageVo,queryVo);
        List<User> userList = pageInfo.getList();
        // 没有找到数据，则抛出NotFound异常，在统一异常中返回404
        if(userList.size() == 0) {
            throw new ResourceNotFoundException();
        }

        System.out.println(userList.get(0).getBirthday().toString());
        PageVo<User> result = new PageVo<>(pageInfo.getPageNum(), pageInfo.getPageSize(),
                pageInfo.getTotal(),  pageInfo.getPages(), pageInfo.getList()
        );

        return R.success().data(result);
    }

    @ResponseStatus(HttpStatus.OK)
    @GetMapping("/{id}")
    public R<User> findById(@PathVariable("id") String id) {
        // 1. 获得参数

        // 2. 业务处理
        User User = userService.selectByPrimaryKey(id);

        // 3. 返回结果
        return R.success().data(User);
    }

    @ResponseStatus(HttpStatus.OK)
    @PutMapping("/{id}")
    public R update(@PathVariable String id, @RequestBody @Validated User user) {
        // 1. 获得参数

        User u = userService.selectByPrimaryKey(id);
        if(u != null){
            u.setName(user.getName());
//            u.setBirthday(user.getBirthday());
//            u.setEmail(user.getEmail());
//            u.setPassword(user.getPassword());
//            u.setPhoneNumber(user.getPhoneNumber());
//            u.setPhoto(user.getPhoto());
//            u.setSalary(user.getSalary());
//            u.setUserName(user.getUserName());
//            u.setWeight(user.getWeight());
        }
        // 2. 业务处理
        userService.updateByPrimaryKey(u);

        // 3. 返回结果
        return R.success();
    }

    //参数ids=1,2,3时，自动解析为一个数组
    //@ResponseStatus(HttpStatus.NO_CONTENT)
    @ResponseStatus(HttpStatus.OK)
    @DeleteMapping("/{ids}")
    public R delete(@PathVariable String[] ids) {
        userService.deleteByIds(ids);
        return R.success();
    }

    @ResponseStatus(HttpStatus.CREATED)
    @PostMapping(value = "", consumes={MediaType.MULTIPART_FORM_DATA_VALUE})
    public R save(@RequestPart User user, @RequestPart("photoFile") MultipartFile photoFile, HttpServletRequest request) throws IOException {
        //指定上传文件存放的根目录
        String fileRootPath = request.getServletContext().getRealPath("uploads");
        File file = new File(fileRootPath);
        if(!file.exists()){
            file.mkdirs();
        }

        //为了避免上传文件重名，可以使用UUID作为文件名
        String uuid = UUID.randomUUID().toString();
        String suffix = photoFile.getOriginalFilename().substring(photoFile.getOriginalFilename().lastIndexOf("."));
        String photoPath = fileRootPath + "\\" + uuid + suffix;
        //保存文件到指定目录
        FileCopyUtils.copy(photoFile.getInputStream(), Files.newOutputStream(new File(photoPath).toPath()));

        // 保存商品
        user.setId(UUID.randomUUID().toString().replace("-", ""));
        // 设置图片文件名
        user.setPhoto(uuid + suffix);
        userService.insert(user);

        return R.success();
    }

    @GetMapping(value="/download")
    public ResponseEntity<byte[]> download(String id, HttpServletRequest request) throws IOException {
        User user = userService.selectByPrimaryKey(id);

        //指定上传文件存放的根目录
        String fileRootPath = request.getServletContext().getRealPath("uploads");
        // 获得上传文件的本地路径
        String filePath = fileRootPath + "\\" + user.getPhoto();

        //响应行
        HttpStatus statusCode = HttpStatus.OK;
        //响应头
        HttpHeaders headers=new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", user.getPhoto());
        //响应体
        byte[] body=null;
        InputStream is = new FileInputStream(filePath);
        body=new byte[is.available()];
        is.read(body);

        //使用ResponseEntity实现文件下载
        return new ResponseEntity<byte[]>(body, headers, statusCode);
    }
}
